package com.loe.ktui.custom

import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.core.content.res.getColorOrThrow
import com.chad.library.adapter.base.BaseQuickAdapter
import com.loe.ktui.MATCH_PARENT
import com.loe.ktui.R
import com.loe.ktui.UiGroup
import com.loe.ktui.util.KtColor
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

open class UiRefreshLayout(id: String? = null) : UiGroup(id)
{
    override var width: Any? = MATCH_PARENT

    var refreshTextColor: Int? = null
    var refreshBgColor: Int? = null

    var onLoadData: (KtRefreshLayout.(isRefresh: Boolean) -> Unit)? = null
    fun onLoadData(onLoadData: KtRefreshLayout.(isRefresh: Boolean) -> Unit)
    {
        this.onLoadData = onLoadData
    }

    var onRefresh: (KtRefreshLayout.() -> Unit)? = null
    fun onRefresh(onRefresh: KtRefreshLayout.() -> Unit)
    {
        this.onRefresh = onRefresh
    }

    open fun initUI(context: Context, view: KtRefreshLayout)
    {
        super.initUI(context, view)

        // 递归子元素
        childs.forEach()
        {
            it.createView(context, view)
        }

        if(refreshTextColor != null || refreshBgColor != null)
        {
            view.setPrimaryColors(refreshBgColor ?: KtColor.alpha, refreshTextColor ?: KtColor.grayDeep)
        }
        onLoadData?.let { view.setOnLoaData { isRefresh -> view.it(isRefresh) } }
        onRefresh?.let { view.setOnRefresh { view.it() } }
    }

    /** 创建view */
    override fun createView(context: Context, parent: ViewGroup?): KtRefreshLayout
    {
        return KtRefreshLayout(context).also()
        {
            initUI(context, it)
            addToParent(parent, it)
        }
    }
}

fun Any.ui_RefreshLayout(id: String? = null, block: (UiRefreshLayout.() -> Unit)? = null): UiRefreshLayout
{
    val ui = UiRefreshLayout(id)
    block?.let { ui.it() }
    if (this is UiGroup) addChild(ui)
    return ui
}

/**
 * 集成刷新布局
 */
open class KtRefreshLayout : SmartRefreshLayout
{
    companion object
    {
        init
        {
            //设置全局的Header构建器
            setDefaultRefreshHeaderCreator()
            { context, layout ->
                if(layout !is KtRefreshLayout)
                {
                    layout.setPrimaryColorsId(android.R.color.transparent, R.color.kt_grayDeep)
                }
                ClassicsHeader(context)
                    .setDrawableSize(18f)
            }
            //设置全局的Footer构建器
            setDefaultRefreshFooterCreator()
            { context, layout ->
                ClassicsFooter(context)
                    .setDrawableSize(15f)
            }
            ClassicsFooter.REFRESH_FOOTER_NOTHING = ""
        }
    }

    constructor(context: Context) : super(context)
    {
        init(null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        init(attrs)
    }

    private fun init(attrs: AttributeSet?)
    {
        setEnableOverScrollBounce(false)
        setDragRate(0.65f)

        context.obtainStyledAttributes(attrs, R.styleable.KtRefreshLayout)?.let()
        {
            setPrimaryColors(
                it.getColor(R.styleable.KtRefreshLayout_kt_refreshBgColor, KtColor.alpha),
                it.getColor(R.styleable.KtRefreshLayout_kt_refreshTextColor, KtColor.grayDeep))
            it.recycle()
        }
    }

    var pageSize: Int = 10

    var page = 1

    var adapter: BaseQuickAdapter<*, *>? = null
        set(value)
        {
            field = value
            for (i in 0 until childCount)
            {
                val v = getChildAt(i)
                if (v is RecyclerView)
                {
                    v.adapter = value
                }
            }

            value?.emptyView = inflate(context, R.layout.kt_list_empty, null)
        }

    var emptyView
        get() = adapter?.emptyView
        set(value)
        {
            adapter?.emptyView = value
        }

    private var onLoadData: ((isRefresh: Boolean) -> Unit)? = null

    /** 设置加载监听 */
    fun setOnLoaData(onLoadData: (isRefresh: Boolean) -> Unit)
    {
        this.onLoadData = onLoadData
        setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener
        {
            override fun onRefresh(refreshLayout: RefreshLayout)
            {
                page = 1
                onLoadData(true)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout)
            {
                onLoadData(false)
            }
        })
    }

    var isRefreshState = false
        set(value)
        {
            field = value
            post()
            {
                setNoMoreData(value)
            }
        }

    /** 设置刷新监听 */
    fun setOnRefresh(onRefresh: () -> Unit)
    {
        isRefreshState = true

        setOnLoaData()
        { isRefresh ->
            if (isRefresh)
            {
                onRefresh()
            }
        }
    }

    fun loadData(isRefresh: Boolean = true)
    {
        if (isRefresh)
        {
            page = 1
        }
        onLoadData?.invoke(isRefresh)
    }

    /**
     * 加载完成调用
     */
    fun loadOk()
    {
        closeHeaderOrFooter()
        if(isRefreshState)
        {
            setNoMoreData(true)
        }
    }

    /**
     * 设置数据
     */
    fun setData(aList: List<*>?, isRefresh: Boolean = true)
    {
//        closeHeaderOrFooter()
        if (aList == null)
        {
            setNoMoreData(true)
        } else
        {
            adapter?.let()
            {
                if (mEnableLoadMore)
                {
                    if (isRefresh)
                    {
                        it.data.clear()
                        setNoMoreData(isRefreshState)
                    }
                    it.addData(aList as List<Nothing>)

                    if (aList.isEmpty() || aList.size < pageSize)
                    {
                        setNoMoreData(true)
                    }
                    page++
                } else
                {
                    it.data.clear()
                    it.addData(aList as List<Nothing>)
                }
            }
        }
    }

//    /**
//     * 加载完成调用
//     */
//    fun loadOk(aList: List<*>? = null)
//    {
//        loadOk(true, aList)
//    }
//
//    /**
//     * 加载完成调用
//     */
//    fun loadOk(isRefresh: Boolean = true, aList: List<*>? = null)
//    {
//        closeHeaderOrFooter()
//        if (aList == null)
//        {
//            setNoMoreData(true)
//        } else
//        {
//            adapter?.let()
//            {
//                if (mEnableLoadMore)
//                {
//                    if (isRefresh)
//                    {
//                        it.data.clear()
//                        setNoMoreData(isRefreshState)
//                    }
//                    it.addData(aList as List<Nothing>)
//
//                    if (aList.isEmpty() || aList.size < pageSize)
//                    {
//                        setNoMoreData(true)
//                    }
//                    page++
//                } else
//                {
//                    it.data.clear()
//                    it.addData(aList as List<Nothing>)
//                }
//            }
//        }
//    }

    /**
     * 加载失败调用
     */
    fun loadError(isRefresh: Boolean = true)
    {
        if (isRefresh)
        {
            finishRefresh(false)
        } else
        {
            finishLoadMore(false)
        }
    }

    /** 单页，隐性无加载 */
    fun singlePage()
    {
        pageSize = Int.MAX_VALUE
    }
}